package com.tweetgraph;

import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;

@SuppressWarnings("serial")
public class TweetGraphServlet extends HttpServlet {

	
	
	public void init() throws ServletException{
		/*
		 * Try to get the list of allowed users from the DB. if no object exists
		 * save the list of allowed users 
		 * 
		 */
		
		try{
//			DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
//			Key userKey = KeyFactory.createKey("UsersTable", "AllowedUsers");
//			
//			Query query = new Query(userKey);
//			List<Entity> userList = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(100));
//			
//			if(userList == null || userList.isEmpty()){
//				/*
//				 * If the user list doesn't exist - insert one with the default values of 
//				 * nish, alexander anton, darren and austin.
//				 */
//				Entity userListEntity = new Entity(userKey);
//				Set<String> userSet = new TreeSet<String>();
//				userSet.add("nishant.vepachedu");
//				userSet.add("darrencknight");
//				userSet.add("nishanth.uc");
//				userSet.add("alexanderalton");
//				userSet.add("austinmichaelcraig");
//				
//				userListEntity.setProperty("userSet", userSet);
//				
//		        datastore.put(userListEntity);
//
//			}
			
			
//			/*
//			 * try querying again:
//			 */
//			userKey = KeyFactory.createKey("UsersTable", "AllowedUsers");
//			query = new Query(userKey);
//			
//			userList = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(100));
//			if(userList.isEmpty()){
//				System.out.println("save unsuccessful!!");
//				
//			}else{
//				System.out.println("Saved!!:" + userList.toString());
//			}
			
			
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 
	 */
	public void service(HttpServletRequest req, HttpServletResponse resp){
		
		/*
		 * Check for user authentication - set an authentication token in the session - if the token is not present
		 * all the servlets must discard requests and kick out
		 */
		
	}
	
}
